package com.atguigu.springcloud.feign;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class MyLoadBanlanceImpl implements MyLoadBanlance {
    private AtomicInteger atomicInteger=new AtomicInteger(0);
    @Override
    public ServiceInstance seviceInstance(List<ServiceInstance> serviceInstances) {
        int index = doAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }

    public int doAndIncrement(){
        int next;
        int current;
        do{
            current=atomicInteger.getAndIncrement();
            next=current>Integer.MAX_VALUE?0:current+1;
        }while(!atomicInteger.compareAndSet(atomicInteger.get(), next));
        log.info("获取的下一个值："+next);
        return next;
    }
}
